package org.algorithm.Backtracking.leetcode40;

import org.algorithm.Stack.ArrayStack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution2 {

    List<List<Integer>> res = new ArrayList<>();
    List<Integer> item = new ArrayList<>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        int n = candidates.length;
        boolean [] used = new boolean[n];
        Arrays.sort(candidates);
        backtracking(candidates,target,0,0,used);
        return res;
    }

    private void backtracking(int [] candidates,int target,int sum,int index,boolean [] used){
        if (sum==target){
            res.add(new ArrayList<>(item));
            return;
        }

        if (sum>target || index>=candidates.length){
            return;
        }

        for (int i = index; i <candidates.length ; i++) {
            if (i>0 && candidates[i]==candidates[i-1] && !used[i-1]){
                continue;
            }
            item.add(candidates[i]);
            used[i]=true;
            backtracking(candidates,target,sum+candidates[i],i+1,used);
            item.remove(item.size()-1);
            used[i]=false;
        }
    }
}
